<?php 
include("helper/DBOperation.php");
$dbObj = new DBOperation();
/* connect to gmail */
$hostname = '{imap.gmail.com:993/ssl/novalidate-cert}INBOX';
$username = 'cemusaheartbeat@gmail.com';
$password = 'Cemusa123';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

/* grab emails */
$yesterday = date("Y-m-d", strtotime ("-7 days"));
$searchQuery = 'SINCE "'.$yesterday.'"';

$emails = imap_search($inbox,$searchQuery);
if($emails) {
	/* put the newest emails on top */
	rsort($emails);
	/* delete old mails */ 
	$dbObj->deleteRecords("tbl_emails", "", "");
	/* for every email... */
	foreach($emails as $email_number) {
		$overview = imap_fetch_overview($inbox,$email_number,0);
		$message = imap_fetchbody($inbox,$email_number,1);
		$insert_keyvalue['id'] = NULL;
		$insert_keyvalue['from'] = $overview[0]->from;
		$insert_keyvalue['subject'] = $overview[0]->subject;;
		$insert_keyvalue['date'] = $overview[0]->date;
		$insert_keyvalue['body'] = $message;
		$dbObj->insertRecords('tbl_emails',$insert_keyvalue);
	}
}
imap_close($inbox);
?>
